import { useCallback, useEffect, useState, useRef } from "react";
import { message, Form } from "antd";

import { hiprint } from "vue-plugin-hiprint";
import { getAllPrinter } from "@/utils/print.jsx";
import { getExpressRelativePrinter, setExpressRelativePrinter } from "@/utils/authority";
import { cloneDeep } from "lodash";

let hiprintTemplate, runner;
export const usePrintLabel = props => {
	const [form] = Form.useForm();
	const [configObj, setConfigObj] = useState({});
	const [printer, setPrinter] = useState("");
	const [printedArr, setPrintedArr] = useState([]);
	const [printData, setPrintData] = useState([]);
	const [template, setTemplate] = useState([]);
	const [printCodes, setPrintCodes] = useState([]);
	const latestRealPrintFunc = useRef(); //手动用ref保存最新的realPrint 然后通过他调用realPrint

	const getPrintDataFunc = async rows => {
		setPrintCodes(rows);
		return new Promise((resolve, reject) => {
			if (props.printType == "Purchase") {
				const selectedOneTemple = {
					panels: [
						{
							paperHeader: 0,
							watermarkOptions: {},
							printElements: [
								{
									printElementType: {
										type: "text",
										title: "条形码"
									},
									options: {
										hCenter: 11.12184715270996,
										testData: "1772155008909275138",
										bottom: 22.62184715270996,
										coordinateSync: false,
										textType: "barcode",
										right: 124.125,
										title: "条形码",
										qrCodeLevel: 0,
										top: 0,
										field: "skuCode",
										left: 1.5,
										width: 140,
										fontSize: 10,
										lineHeight: 10,
										widthHeightSync: false,
										vCenter: 61.875,
										height: 21
									}
								},
								{
									printElementType: {
										type: "text",
										title: "采购单号"
									},
									options: {
										hCenter: 11.12184715270996,
										testData: "1772155008909275138",
										bottom: 22.62184715270996,
										coordinateSync: false,
										textType: "qrcode",
										left: 160,
										title: "采购单号",
										qrCodeLevel: 0,
										top: 20,
										field: "purchaseOrderNo",
										width: 40,
										fontSize: 10,
										lineHeight: 10,
										widthHeightSync: false,
										vCenter: 61.875,
										height: 40
									}
								},
								{
									printElementType: {
										type: "text",
										title: "采购单号"
									},
									options: {
										hCenter: 11.12184715270996,
										testData: "1772155008909275138",
										bottom: 22.62184715270996,
										title: "采购单号",
										hideTitle: true,
										top: 70,
										left: 160,
										field: "purchaseOrderNo",
										width: 50,
										fontSize: 10,
										lineHeight: 10,
										vCenter: 61.875,
										height: 12
									}
								},
								{
									printElementType: {
										type: "text",
										title: "系统商品名称"
									},
									options: {
										hCenter: 73.24684143066406,
										testData: "未开启绑定一对一测试",
										top: 45.5,
										field: "skuName",
										left: 0,
										bottom: 81.24684143066406,
										width: 140,
										right: 72.75,
										title: "系统商品名称",
										vCenter: 36.75,
										height: 12
									}
								},
								{
									printElementType: {
										type: "text",
										title: "供应商名称"
									},
									options: {
										hCenter: 73.24684143066406,
										testData: "未开启绑定一对一测试",
										top: 67.5,
										field: "supplierName",
										// hideTitle: true,
										left: 0,
										bottom: 81.24684143066406,
										width: 140,
										right: 72.75,
										title: "供应商名称",
										vCenter: 36.75,
										height: 12
									}
								}
							],
							paperFooter: 85.03937007874016,
							paperNumberContinue: true,
							name: 1,
							width: 75,
							index: 0,
							paperNumberLeft: 136.5,
							paperNumberDisabled: true,
							paperNumberTop: 64.5,
							height: 30
						}
					]
				};
				setTemplate(selectedOneTemple);
				resolve([selectedOneTemple, rows]);
			} else if (props.printType == "Warehoue") {
				const selectedOneTemple = {
					panels: [
						{
							paperHeader: 0,
							watermarkOptions: {},
							printElements: [
								{
									printElementType: {
										type: "text",
										title: "条形码"
									},
									options: {
										hCenter: 11.12184715270996,
										testData: "1772155008909275138",
										bottom: 22.62184715270996,
										coordinateSync: false,
										textType: "barcode",
										right: 124.125,
										title: "条形码",
										qrCodeLevel: 0,
										top: 0,
										field: "skuCode",
										left: 1.5,
										width: 140,
										fontSize: 10,
										lineHeight: 10,
										widthHeightSync: false,
										vCenter: 61.875,
										height: 21
									}
								},
								{
									printElementType: {
										type: "text",
										title: "入库单号"
									},
									options: {
										hCenter: 11.12184715270996,
										testData: "1772155008909275138",
										bottom: 22.62184715270996,
										coordinateSync: false,
										textType: "qrcode",
										left: 160,
										title: "入库单号",
										qrCodeLevel: 0,
										top: 20,
										field: "inboundOrderNo",
										width: 40,
										fontSize: 10,
										lineHeight: 10,
										widthHeightSync: false,
										vCenter: 61.875,
										height: 40
									}
								},
								{
									printElementType: {
										type: "text",
										title: "入库单号"
									},
									options: {
										hCenter: 11.12184715270996,
										testData: "1772155008909275138",
										bottom: 22.62184715270996,
										title: "入库单号",
										hideTitle: true,
										top: 70,
										left: 160,
										field: "inboundOrderNo",
										width: 50,
										fontSize: 10,
										lineHeight: 10,
										vCenter: 61.875,
										height: 12
									}
								},
								{
									printElementType: {
										type: "text",
										title: "系统商品名称"
									},
									options: {
										hCenter: 73.24684143066406,
										testData: "未开启绑定一对一测试",
										top: 45.5,
										field: "skuName",
										left: 0,
										bottom: 81.24684143066406,
										width: 140,
										right: 72.75,
										title: "系统商品名称",
										vCenter: 36.75,
										height: 12
									}
								},
								{
									printElementType: {
										type: "text",
										title: "供应商名称"
									},
									options: {
										hCenter: 73.24684143066406,
										testData: "未开启绑定一对一测试",
										top: 67.5,
										field: "supplierName",
										left: 0,
										bottom: 81.24684143066406,
										width: 140,
										right: 72.75,
										title: "供应商名称",
										vCenter: 36.75,
										height: 12
									}
								}
							],
							paperFooter: 85.03937007874016,
							paperNumberContinue: true,
							name: 1,
							width: 75,
							index: 0,
							paperNumberLeft: 136.5,
							paperNumberDisabled: true,
							paperNumberTop: 64.5,
							height: 30
						}
					]
				};
				setTemplate(selectedOneTemple);
				resolve([selectedOneTemple, rows]);
			} else if (props.printType == "ReturnGoods") {
				const selectedOneTemple = {
					"panels": [
							{
									"index": 0,
									"name": 1,
									"height": 40,
									"width": 60,
									"paperHeader": 0,
									"paperFooter": 113.38582677165356,
									"printElements": [
											{
													"options": {
															"left": 1.5,
															"top": 0,
															"height": 27,
															"width": 121.5,
															"field": "uniqueCode",
															"right": 95.25,
															"title": "条形码",
															"bottom": 23.25,
															"fields": [
																	{
																			"text": "商品唯一码",
																			"field": "uniqueCode"
																	},
																	{
																			"text": "无头码",
																			"field": "headCode"
																	},
																	{
																			"text": "商品门店名称",
																			"field": "refundStoreName"
																	},
																	{
																			"text": "商品门店地址",
																			"field": "refundStoreAddress"
																	},
																	{
																			"text": "退货员",
																			"field": "refundName"
																	},
																	{
																			"text": "退货快递单号",
																			"field": "refundLogisticsNo"
																	},
																	{
																			"text": "退货快递名称",
																			"field": "refundLogisticsCompany"
																	},
																	{
																			"text": "退货备注",
																			"field": "refundRemark"
																	},
																	{
																			"text": "退货商品名称",
																			"field": "refundGoodsName"
																	},
																	{
																			"text": "店铺订单号",
																			"field": "outOrderSn"
																	},
																	{
																			"text": "系统订单号",
																			"field": "omsOrderSn"
																	},
																	{
																			"text": "订单备注",
																			"field": "orderRemark"
																	},
																	{
																			"text": "订单快递公司",
																			"field": "logisticsCompany"
																	},
																	{
																			"text": "波次名称",
																			"field": "waveName"
																	},
																	{
																			"text": "波次类型",
																			"field": "waveType"
																	},
																	{
																			"text": "订单商品价格",
																			"field": "orderPrice"
																	},
																	{
																			"text": "订单所属店铺",
																			"field": "ecStoreName"
																	},
																	{
																			"text": "门店名称",
																			"field": "storeName"
																	}
															],
															"hCenter": 11.25,
															"vCenter": 47.25,
															"fontSize": 10,
															"testData": "XS888888888",
															"textType": "barcode",
															"lineHeight": 10,
															"qrCodeLevel": 0,
															"coordinateSync": false,
															"widthHeightSync": false
													},
													"printElementType": {
															"title": "条形码",
															"type": "text"
													}
											},
											{
													"options": {
															"left": 0,
															"top": 46,
															"height": 33,
															"width": 162,
															"right": 158.25,
															"field": "skuCode",
															"title": "系统商品编码",
															"bottom": 67,
															"hCenter": 50.5,
															"vCenter": 77.25,
															"qrCodeLevel": 0,
															"hideTitle": true,
															"coordinateSync": false,
															"widthHeightSync": false
													},
													"printElementType": {
															"title": "自定义文本",
															"type": "text"
													}
											},
											{
													"options": {
															"left": 0,
															"top": 60,
															"height": 10.5,
															"width": 163.5,
															"field": "skuName",
															"right": 72.25000762939453,
															"title": "系统商品名称",
															"bottom": 77.75,
															"hCenter": 72.5,
															"vCenter": 36.25000762939453,
															"testData": "系统商品名称",
															"hideTitle": true
													},
													"printElementType": {
															"title": "门店区域编码",
															"type": "text"
													}
											},
											{
													"options": {
															"left": 0,
															"top": 85,
															"height": 13.5,
															"width": 144,
															"right": 144.75,
															"field": "supplierName",
															"title": "供应商名称",
															"bottom": 93.5,
															"hCenter": 86.75,
															"vCenter": 72.75,
															"qrCodeLevel": 0,
															"hideTitle": true,
															"coordinateSync": false,
															"widthHeightSync": false
													},
													"printElementType": {
															"title": "自定义文本",
															"type": "text"
													}
											},
									],
									"paperNumberLeft": 136.5,
									"paperNumberTop": 64.5,
									"paperNumberDisabled": true,
									"paperNumberContinue": true,
									"watermarkOptions": {}
							}
					]
			};
				setTemplate(selectedOneTemple);
				resolve([selectedOneTemple, rows]);
			}
		});
	};
	const printAction = ([__template, __printData, printer]) => {
		console.log(__template, __printData, printer, '123213123');
		if (__printData && __printData.length) {
			const tasks = [];
			__printData.map((printDataItem, index) => {
				tasks.push(done => {
					latestRealPrintFunc.current(runner, done, index, printer);
				});
			});
			runner.addMultiple(tasks);
			message.success(`即将打印${__printData.length}个${props.printName}，请等待`);
		} else {
			return message.info("打印数据为空");
		}
	};
	//打印队列渲染输出
	const realPrint = (runner, done, index, printer) => {
		console.log(runner, done, index, printer, 'runneer')
		const printDataItem = printData[index];
		console.log(printData, printDataItem, template, 'item')
		if (!printDataItem || !template) {
			return message.error(`未获取到${props.printName}`);
		}

		hiprintTemplate = new hiprint.PrintTemplate({ template });

		hiprintTemplate.on("printSuccess", function () {
			let list = [];
			list.push(printDataItem);
			setPrintedArr(list);
			console.log(printDataItem, "printDataItem");
			// 打印成功后请求接口通知后端修改打印状态
			if (props.printType == "Warehoue") {
				props.printUpdateRequest &&
					props
						.printUpdateRequest([
							{
								inboundOrder: printDataItem.inboundOrderNo,
								printNum: printDataItem.originalNum
							}
						])
						.then(({ res }) => {});
			}
			done();
			props.callback && props.callback(printData.length);
		});
		hiprintTemplate.on("printError", function () {
			if (!runner?.tasks?.list?.length) {
				setPrintedArr([]);
			}
			done();
		});
		hiprintTemplate.print2(printDataItem, { printer });
	};
	latestRealPrintFunc.current = realPrint; //手动用ref保存最新的realPrint 然后通过他调用realPrint

	/**
	 *
	 * @param {*} printData 数组[], 数组内的元素如下
	 * {skuCode:"条形码",  codeSN:"序号" ,orderGoodsCount:"订单商品数量",orderGoodsName:"订单商品名称",orderGoodsSpec:"订单规格属性",salesOrderSn:"销售出库单号"}
	 */
	const printUniqueCode = rows => {
		setPrintData(cloneDeep(rows));
		if (!runner) {
			runner = new TaskRunner();
			runner.setConcurrency(1); // 同时执行数量
		}
		const printerConfigs = getExpressRelativePrinter();
		if (printerConfigs) {
			const labelPrinter = printerConfigs[props.printName];
			if (!labelPrinter) {
				return message.warning(`请先设置${props.printName}关联的打印机`);
			}
		}

		getAllPrinter(currentPrinters => {
			if (currentPrinters.includes(labelPrinter)) {
				getPrintDataFunc(rows).then(printAction);
			} else {
				return message.warning(`${props.printName}关联的打印机${labelPrinter}未开启`);
			}
		});
	};

	const [printerList, setPrinterList] = useState([]); //打印机列表
	const [labelPrinter, setLabelPrinter] = useState(""); //唯一码打印机

	const initPrint = rows => {
		console.log(rows, 'rows')
		setPrintData(cloneDeep(rows));
		if (!runner) {
			runner = new TaskRunner();
			runner.setConcurrency(1); // 同时执行数量
		}
		const printerConfigs = getExpressRelativePrinter();
		if (printerConfigs) {
			const __labelPrinter = printerConfigs[props.printName];
			setLabelPrinter(__labelPrinter);
		}
		getAllPrinter(currentPrinters => {
			setPrinterList(currentPrinters);
		});
		getPrintDataFunc(rows);
	};

	useEffect(() => {
		// 从缓存中取出快递和打印机配置数据
		const obj = getExpressRelativePrinter() || {};
		setConfigObj(obj);
		form.setFieldsValue({ ...obj });
	}, []);

	const setLabelRelativePrinter = name => {
		if (configObj) {
			setExpressRelativePrinter({
				...configObj,
				[props.printName]: name
			});
		}
	};

	return {
		// 一步打印，不弹窗
		printUniqueCode, //

		// 以下是分步骤进行的，参见
		// src\views\purchase\FmcmPurchase\component\PrintModal.jsx
		initPrint,
		printData,
		template,
		printerList,
		labelPrinter,
		configObj,
		getPrintDataFunc,
		printAction,
		getExpressRelativePrinter,
		setLabelRelativePrinter
	};
};
